package com.caiyi.financial.nirvana.sms.gateway.sgip;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * 监听SGIP协议的上行消息，包括deliver和report消息
 */
public class SGIPServer implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(SGIPServer.class);

    public static final int TIMEOUT = 30;

    private int localPort;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private SGIPClient client;

    public SGIPServer(int port, SGIPClient client) {
        this.localPort = port;
        this.client = client;
    }

    public void run() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new SGIPServerInitializer(client));
            logger.info("SGIP协议上行消息监听服务器启动，监听端口：" + localPort);
            ChannelFuture f = b.bind(localPort).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            logger.error("SGIPServer error ", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public void kill() {
        if (null != bossGroup) {
            bossGroup.shutdownGracefully();
        }
        if (null != workerGroup) {
            workerGroup.shutdownGracefully();
        }
    }

}
